package com.gzy.mylog.modules.log;


import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemSwipeListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.gzy.mylog.BaseFragment;
import com.gzy.mylog.R;
import com.gzy.mylog.events.AddLogEvent;
import com.gzy.mylog.events.DeleteLogEvent;
import com.gzy.mylog.events.LogoutEvent;
import com.gzy.mylog.events.UpdateLogEvent;
import com.gzy.mylog.manager.AuthManager;
import com.gzy.mylog.model.Log;
import com.gzy.mylog.model.PageList;
import com.gzy.mylog.model.Result;
import com.gzy.mylog.net.LogApi;
import com.gzy.mylog.net.core.XXModelCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import okhttp3.Call;

import static androidx.constraintlayout.widget.Constraints.TAG;

/**
 * A simple {@link Fragment} subclass.
 */
public class LogFragment extends BaseFragment {

    RecyclerView recyclerView;
    SwipeRefreshLayout swipeRefreshLayout;
    LogAdapter logAdapter;
    private List<Log> dataList = new ArrayList<>();
    int currPage = 1;

    public LogFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_log, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView = view.findViewById(R.id.recyclerView);
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);

        initRecyclerView();
        loadData();

        view.findViewById(R.id.rl_add).setOnClickListener((v)->{
            getActivity().startActivity(new Intent(getContext(),AddLogActivity.class));
        });
        EventBus.getDefault().register(this);
    }

    private void loadData() {

        LogApi.loadLog(AuthManager.loadToken(getContext()), 1, 10, new XXModelCallback<Result<PageList<Log>>>(new TypeReference<Result<PageList<Log>>>() {
        }) {
            @Override
            public void onResponseData(Call call, Result<PageList<Log>> model) {
                List<Log> data = model.getData().getData();
                dataList.clear();
                dataList.addAll(data);
                logAdapter.setNewData(data);
                swipeRefreshLayout.setRefreshing(false);
                currPage = 1;
            }

            @Override
            public void onFailure2(Call call, IOException e, ErrType type, String message) {
                Toast.makeText(getContext(), "" + message, Toast.LENGTH_SHORT).show();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    private void initRecyclerView() {
        logAdapter = new LogAdapter(dataList);

        logAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Toast.makeText(getContext(), "" + position, Toast.LENGTH_SHORT).show();
                Log log = dataList.get(position);
                Intent intent = new Intent(getContext(),UpdateLogActivity.class);

                intent.putExtra("id",log.getId());
                intent.putExtra("content",log.getContent());

                startActivity(intent);

            }
        });


        // 下拉刷新
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 执行下拉刷新获取数据的事情
                loadData();

            }
        });

        // 上拉加载更多
        //        logAdapter.getLoadMoreModule().setEnableLoadMore(true);
        //        logAdapter.getLoadMoreModule().setEnableLoadMore(true);
        logAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMore();
            }
        });
        // 加载数据


        //设置布局方式
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //解决数据加载不完的问题
        //        mRecyclerView.setNestedScrollingEnabled(false);
        //添加分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(logAdapter);

        // 开启滑动删除
//        logAdapter.getDraggableModule().setSwipeEnabled(true);
//        logAdapter.getDraggableModule().setOnItemSwipeListener(new OnItemSwipeListener() {
//            @Override
//            public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {
//                Toast.makeText(getContext(), "" + pos, Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {
//                Toast.makeText(getContext(), "" + pos, Toast.LENGTH_SHORT).show();
//
//            }
//
//            @Override
//            public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {
//                Toast.makeText(getContext(), "" + pos, Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {
//
//            }
//        });

    }

    private void loadMore() {
        //        Toast.makeText(getContext(), "触发率 加载更多的事件", Toast.LENGTH_SHORT).show();
        //        logAdapter.getLoadMoreModule().loadMoreEnd();
        android.util.Log.e(TAG, "loadMore: " + (currPage + 1));
        LogApi.loadLog(AuthManager.loadToken(getContext()), currPage + 1, 10, new XXModelCallback<Result<PageList<Log>>>(new TypeReference<Result<PageList<Log>>>() {
        }) {
            @Override
            public void onResponseData(Call call, Result<PageList<Log>> model) {
                //                logAdapter.getLoadMoreModule().load

                if (model.getData().getData().size() == 0) {
                    logAdapter.getLoadMoreModule().loadMoreEnd();
                } else {
                    currPage = model.getData().getCurrPage();
                    logAdapter.addData(model.getData().getData());
                    logAdapter.getLoadMoreModule().loadMoreComplete();
                }
            }

            @Override
            public void onFailure2(Call call, IOException e, ErrType type, String message) {
                logAdapter.getLoadMoreModule().loadMoreFail();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void addLogEvent(AddLogEvent event) {
        loadData();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateLogEvent(UpdateLogEvent event) {
        loadData();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void deleteLogEvent(DeleteLogEvent event) {
        loadData();
    }
}
